package com.iefgames.cs.comet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import com.iefgames.cs.framework.exception.CometDisconnectException;
import com.iefgames.cs.manager.CometManager;
import com.iefgames.cs.shout.Shout;

public abstract class AbstractComet {
	protected static Log logger = LogFactory.getLog(AbstractComet.class);
	
	protected abstract void comet(HttpServletRequest request, HttpServletResponse response);
	
	protected abstract void initComet(HttpServletRequest request, HttpServletResponse response);
	
	protected abstract String output(Vector shouts);
	
	protected void newComet(String uuid, Continuation continuation) {
		continuation.setObject(new Vector<Shout>());
		CometManager.set(uuid, continuation);
	}
	
	protected void fire(HttpServletRequest request, 
			HttpServletResponse response) {
		Continuation continuation = ContinuationSupport.getContinuation(request, null);
		
		Vector shouts = (Vector) continuation.getObject();
		
		if (shouts.isEmpty()) {
			headbear(request, response);
			return;
		}
		
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.append(output(shouts));
			writer.checkError();
//			writer.flush();
		} catch (IOException ioe) {
			//连接在沉睡期间已经断开，那么释放与连接有关的资源
			if (writer != null) {
				writer.close();
			}
			
			throw new CometDisconnectException(request, response, ioe);
		}

		shouts.removeAllElements();
	}

	//from internet
	protected void setNoCacheHeader(HttpServletResponse response) {
		response.setContentType("text/html; charset=utf-8");
		// Set to expire far in the past.
		response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");

		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");

		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
	}

	
	protected void sleep(Continuation continuation) {
		if (continuation.isPending()) {
			continuation.reset();
		}
		
		continuation.suspend(CometManager.SUSPEND_TIME);
	}
	
	private void headbear(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.println(" ");
			writer.checkError();
			
			logger.info("/headbear");
		} catch (IOException ioe) {
			//连接在沉睡期间已经断开，那么释放与连接有关的资源
			if (writer != null) {
				writer.close();
			}
			
			throw new CometDisconnectException(request, response, ioe);
		}
	}
	
	protected static String getHeadString() {
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" ");
		sb.append("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
		sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
		sb.append("<head>\n");
		sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>\n");
		sb.append("<meta http-equiv=\"Pragma\" content=\"no-cache\" />\n");
		sb.append("<script type='text/javascript'>");
		sb.append("document.domain='iefgames.com';");
		sb.append("var _ = window.parent.Iefgames_CS._;");
		sb.append("</script>");
		sb.append("</head>");
		sb.append("<body>");
		
		return sb.toString();
	}
}
